<script setup>
import { ref } from 'vue'
import { passwordUpdateService } from '@/api/user.js'
import { useRouter } from 'vue-router'
import { useUserInfoStore } from '@/stores/userInfo'
import { useTokenStore } from '@/stores/token'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const userInfoStore = useUserInfoStore()
const tokenStore = useTokenStore()

const pwd = ref({
    old_pwd: '',
    new_pwd: '',
    re_pwd: ''
})

const rePasswordValid = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请再次输入密码'))
    } else if (value !== pwd.value.new_pwd) {
        callback(new Error('两次密码不一致'))
    } else {
        callback()
    }
}

const rules = ref({
    old_pwd: [
        { required: true, message: '请输入旧密码', trigger: 'blur' },
        { min: 5, max: 16, message: '密码的长度必须为5-16位', trigger: 'blur' }
    ],
    new_pwd: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 5, max: 16, message: '密码的长度必须为5-16位', trigger: 'blur' }
    ],
    re_pwd: [
        { validator: rePasswordValid, trigger: 'blur' }
    ]
})

const formRef = ref(null) // 获取表单实例

const passwordUpdate = () => {
    // 使用 formRef.value.validate 进行表单校验
    formRef.value.validate((valid) => {
        if (valid) { // 校验通过
            ElMessageBox.confirm(
                '你确定要修改吗?',
                '温馨提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
                .then(async () => {
                    try {
                        await passwordUpdateService(pwd.value)
                        ElMessage.success('修改成功，请重新登录')
                        router.push('/login')
                        tokenStore.removeToken()
                        userInfoStore.removeInfo()
                    } catch (error) {
                      // 捕获请求错误，并显示错误信息
                        ElMessage.error(error.response?.data?.message || '修改密码失败');
                    }
                })
                .catch(() => {
                    ElMessage({
                        type: 'info',
                        message: '取消',
                    })
                })
        } else { // 校验不通过
            // ElMessage.error('请检查参数'); // 提示用户检查表单
            return false; // 阻止后续操作
        }
    })
}
</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>重置密码</span>
            </div>
        </template>
        <el-row>
            <el-col :span="6">
                <el-form ref="formRef" :model="pwd" :rules="rules" label-width="100px" size="large">
                    <el-form-item label="旧密码" prop="old_pwd">
                        <el-input type="password" v-model="pwd.old_pwd" placeholder="请输入旧密码"></el-input>
                    </el-form-item>
                    <el-form-item label="新密码" prop="new_pwd">
                        <el-input type="password" v-model="pwd.new_pwd" placeholder="请输入新密码"></el-input>
                    </el-form-item>
                    <el-form-item label="重复新密码" prop="re_pwd">
                        <el-input type="password" v-model="pwd.re_pwd" placeholder="请再次输入新密码"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="passwordUpdate()">提交修改</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
    </el-card>
</template>